package cn.lopr.im.android.mvp.presenter;

import androidx.fragment.app.Fragment;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import cn.lopr.im.android.bean.CallbackResult;
import cn.lopr.im.android.bean.User;
import cn.lopr.im.android.common.OnCallBackListener;
import cn.lopr.im.android.mvp.contact.IContactContact;
import cn.lopr.im.android.mvp.model.ContactModel;
import cn.lopr.im.android.mvp.view.adapters.base.CharacterParser;
import cn.lopr.im.android.mvp.view.adapters.base.PinyinComparator;
import cn.lopr.im.android.utils.UiUtils;

/**
 * @author shuangyang7
 * @date 2020/12/19 11:51
 */
public class ContactPresenterImpl implements IContactContact.IContactPresenter {

    /**
     * 登录业务实现者，数据处理的操作者
     */
    private final IContactContact.IContactView contactView;
    private final IContactContact.IContactModel contactModel;

    private final PinyinComparator pinyinComparator;

    private final CharacterParser characterParser;

    private final Fragment fragment;

    /**
     * 在构造方法中实例化model对象
     */
    public ContactPresenterImpl(Fragment fragment, IContactContact.IContactView contactView) {
        this.contactView = contactView;
        this.contactModel = new ContactModel();
        this.pinyinComparator = new PinyinComparator();
        this.characterParser = CharacterParser.getInstance();
        this.fragment = fragment;
    }

    @Override
    public void getFriend() {

        if (!UiUtils.isNetworkAvailable()) {
            contactView.showNetworkError();
            return;
        }

        contactModel.getFriend(this.contactView.getToken(this.fragment.getContext()), new OnCallBackListener<CallbackResult<List<User>>, String>() {
            @Override
            public void success(CallbackResult<List<User>> result) {

                List<User> users = setDataPinyinFirstLetter(result.getData());

                Collections.sort(users, pinyinComparator);

                contactView.getFriendSuccess(users);
            }

            @Override
            public void failure(String errMsg) {
                contactView.showVerifyFailed(errMsg);

            }
        });
    }

    /**
     * 设置数据的拼音首字符
     */
    private List<User> setDataPinyinFirstLetter(List<User> users) {
        if (users == null || users.isEmpty()) {
            return new ArrayList<>();
        }
        for (User user : users) {
            //汉字转换成拼音
            String pinyin = characterParser.getSelling(user.getNickname());
            String sortString = pinyin.substring(0, 1).toUpperCase();

            // 正则表达式，判断首字母是否是英文字母
            if (sortString.matches("[A-Z]")) {
                user.setSortLetters(sortString.toUpperCase());

            } else {
                user.setSortLetters("#");

            }

        }

        return users;
    }

}
